var path = require("path");
var fs = require("fs");

var dirname = '';

if(__dirname.split('/').pop() === 'utils'){
  dirname = path.join(__dirname , '..');
}else{
  dirname = __dirname;
}

var baseDirPath = path.join(dirname , '/public/assets/images/icon');
var scssPath = path.join(dirname , '/src/styles/public/_icon-image.scss');
var iconListPath = path.join(dirname , '/src/config/icons/img-icon.js');

var scssStyle = `
.img-icon{
  display: inline-block;
  width: 16px;
  height: 16px;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

$--img-icon-base-url: '/assets/images/icon/';
`;
var iconList = [];
var success = 0;

fs.readdir(baseDirPath, function(err, dirs){
  if(!err){
    dirs.forEach(function(dirName){
      fs.readdir(baseDirPath + '/' + dirName , function(err  , files){
        if(!err){
          files.forEach(function(fileName){
            var nameArr = fileName.split('.');
            nameArr.pop();
            var name = nameArr.join('.');
            scssStyle += `
.img-icon-${dirName}-${name}{
  background-image: url($--img-icon-base-url + '/${dirName}/${fileName}'); 
}`
            iconList.push(`img-icon img-icon-${dirName}-${name}`);
          })
          success++;
          if(success >= dirs.length){
            fs.writeFile(scssPath , scssStyle , {
              encoding: 'utf-8'
            },function(err){
              if(!err){
                console.log('scss文件写入成功。')
              }
            })
            fs.writeFile(iconListPath , 
`// 1、将图片放在/public/assets/images/icon/ 下面的目录内(可新建目录)
// 2、在项目根目录执行 node utils/createIcon.js 或 npm run createIcon 即可自动生成

export default ${JSON.stringify(iconList , null , 2)}
            ` , {
              encoding: 'utf-8'
            },function(err){
              if(!err){
                console.log('iconList文件写入成功。')
              }
            })
          }
        }
      });
    })
  }
});
